library temp;


import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'dart:convert';

part 'decod.dart';

const adTab = [ 291.771, 277.323, 263.484, 250.240, 237.579, 225.487, 213.948, 202.946,
192.463, 182.483, 172.987, 163.957, 155.375, 147.224, 139.484, 132.139, 125.172, 118.565,
112.301, 106.366, 100.743, 95.418, 90.375, 85.600, 81.081, 76.805, 72.758, 68.929, 65.307, 
61.880, 58.640, 55.574, 52.675, 49.933, 47.340, 44.888, 42.568, 40.375, 38.300, 36.338,
34.481, 32.725, 31.064, 29.493, 28.006, 26.599, 25.267, 24.006, 22.813, 21.684, 20.614,
19.602, 18.642, 17.734, 16.873, 16.058, 15.285, 14.552, 13.858, 13.199, 12.575, 11.982,
11.421, 10.888, 10.382, 9.891, 9.446, 9.013, 8.602, 8.211, 7.840, 7.488, 7.153, 6.834,
6.531, 6.243, 5.969, 5.709, 5.460, 5.224, 5.000, 4.785, 4.582, 4.387, 4.202, 4.026, 3.858,
3.698, 3.545, 3.399, 3.260, 3.127, 3.001, 2.880, 2.764, 2.654, 2.549, 2.448, 2.352, 2.260,
2.172, 2.088, 2.008, 1.931, 1.858, 1.794, 1.720, 1.655, 1.594, 1.534, 1.478, 1.424, 1.372, 
1.322, 1.274, 1.228, 1.184, 1.142, 1.102, 1.063, 1.025, 0.990, 0.955, 0.922, 0.891, 0.860,
0.831, 0.803, 0.776, 0.750, 0.725, 0.701, 0.678, 0.656, 0.634, 0.614, 0.594, 0.575, 0.556,
0.539, 0.522, 0.505, 0.489, 0.474, 0.459, 0.445, 0.431, 0.418, 0.405, 0.393, 0.381, 0.370,
0.359, 0.348, 0.338, 0.328, 0.318, 0.309, 0.300, 0.292, 0.283, 0.275, 0.267, 0.260, 0.252,
0.245, 0.238, 0.232, 0.225, 0.219, 0.213, 0.207, 0.202, 0.196, 0.191, 0.186, 0.181, 0.176,
0.172, 0.167, 0.163
];
double getTemp(double ad) {
  ad = (ad * 2) / (4096 - ad);
  int pos = findClosestIndex(adTab, ad);
  if (pos<0 || pos>180) {
    return -100;
  }
  double begin = adTab[pos];
  if (begin < ad) {
    pos --;
    if (pos < 0)  return -55;
    begin = adTab[pos];
  }
  if (pos+1 > 180)  return 125;
  double end = adTab[pos+1];
  return pos - 55 + (ad-begin)/(end-begin);
}

int findClosestIndex(List<double> ad, double target) {
  int left = 0;
  int right = ad.length - 1;
  int result = -1;

  while (left <= right) {
    int mid = (left + right) ~/ 2;

    if (ad[mid] < target) {
      result = mid; 
      right = mid - 1; 
    } else {
      left = mid + 1;
    }
  }

  return result;
}